#include<iostream>
#include<queue>
#include<cstring>
#include<vector>
//850
using namespace std;
using PII = pair<int, int>;

const int N = 2e5 + 10;

int n, m;
int h[N], e[N], ne[N], w[N], idx;
int dist[N];
bool state[N];

void add(int a, int b, int c){
    e[idx] = b;
    w[idx] = c;
    ne[idx] = h[a];
    h[a] = idx++;
}

int dijkstra(){
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;

    priority_queue<PII, vector<PII>, greater<PII>> heap;
    heap.push({0, 1});

    while(heap.size()){
        PII temp = heap.top();
        heap.pop();

        int ver = temp.second, dis = temp.first;
        if(state[ver]) continue;

        state[ver] = true;

        for (int u = h[ver]; u != -1; u = ne[u]){
            int k = e[u];
            if(dist[k] > dis + w[u]){
                dist[k] = dis + w[u];
                heap.push({dist[k], k});
            }
        }
    }

    if(dist[n] == 0x3f3f3f3f){
        return -1;
    }else{
        return dist[n];
    }
}

int main(){
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);

    memset(h, -1, sizeof h);

    cin >> n >> m;

    for (int i = 0; i < m; i ++){
        int x, y, z;
        cin >> x >> y >> z;
        add(x, y, z);
    }

    int k = dijkstra();
    cout << k << endl;

    return 0;
}